package com.yonyou.jrmob.contacts.schedule.view.date;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 *
 */
public class CalendarCard extends View {

	private static final int TOTAL_COL = 7; // 7列
	private static final int TOTAL_ROW = 6; // 6行
	private Paint mCirclePaint; // 圆圈背景
	private Paint mTextPaint; // 字体
	private int mViewWidth; // 视图宽
	private int mViewHeight; // 视图高
	private int mCellSpace; // ???????
	private int mCellSpaceHeight;
	private Row rows[] = new Row[TOTAL_ROW]; //
	private static CustomDate mShowDate; // 年月日实体类
	private OnCellClickListener mCellClickListener; // 日历的点击事件
	private int touchSlop; //
	private boolean callBackCellSpace;
	private Cell mClickCell;
	private float mDownX;
	private float mDownY;
	private int col, row;
	public static String checkedDay;// 选择的日期
	public List<Date> list;
	private List<String> haveScheduleList;
	private Calendar now = Calendar.getInstance();

	/**
	 *点击事件的接口
	 *
	 */
	public interface OnCellClickListener {
		void clickDate(CustomDate date);

		void changeDate(CustomDate date);
	}

	/*public CalendarCard(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init(context);
	}*/

	/*public CalendarCard(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}*/

	public CalendarCard(Context context) {
		super(context);
		init(context);
	}
	public CalendarCard(Context context, OnCellClickListener listener, List<Date> list, List<String> ScheduleList) {
		super(context);
       // Log.e("lzq","CalendarCard");
		this.mCellClickListener = listener;
		this.list = list;
		haveScheduleList = ScheduleList;
		init(context);
	}

	/*public CalendarCard(Context context, List<Date> list) {
		super(context);
		this.list = list;
		init(context);
	}*/

	private void init(Context context) {
		mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
		initDate();
	}

	private void initDate() {
		mShowDate = new CustomDate();
		fillDate();
	}

	private void fillDate() {

		int monthDay = DateUtil.getCurrentMonthDay(); //当天
		int lastMonthDays = DateUtil.getMonthDays(mShowDate.year, mShowDate.month - 1); // 上月的天数
		int currentMonthDays = DateUtil.getMonthDays(mShowDate.year, mShowDate.month); //本月的天数
		int firstDayWeek = DateUtil.getWeekDayFromDate(mShowDate.year, mShowDate.month);// 第一周第一天
		boolean isCurrentMonth = false;
		if (DateUtil.isCurrentMonth(mShowDate)) {
			isCurrentMonth = true;
		}
		int day = 0;

		for (int j = 0; j < TOTAL_ROW; j++) {
			rows[j] = new Row(j);
			for (int i = 0; i < TOTAL_COL; i++) {
				int position = i + j * TOTAL_COL; //
				//
				if (position >= firstDayWeek && position < firstDayWeek + currentMonthDays) {
					day++;
					rows[j].cells[i] = new Cell(CustomDate.modifiDayForObject(mShowDate, day), State.CURRENT_MONTH_DAY, i, j);
					//
					if (isCurrentMonth && day == monthDay) {
						CustomDate date = CustomDate.modifiDayForObject(mShowDate, day);
						rows[j].cells[i] = new Cell(date, State.TODAY, i, j);
					}
					if (isCurrentMonth && day > monthDay) { // ????????????????????????
						rows[j].cells[i] = new Cell(CustomDate.modifiDayForObject(mShowDate, day), State.UNREACH_DAY, i, j);
					}
					if ((position != 0) || (day == 1 && i == 0 && j == 0 && !isCurrentMonth)) {// ????????
						if ((i == col && j == row)) {
							CustomDate date = CustomDate.modifiDayForObject(mShowDate, day);
							rows[j].cells[i] = new Cell(date, State.CHECKED_DAY, i, j);
							checkedDay = day + "";
						}
					}

					for (int k = 0; k < list.size(); k++) {
						now.setTime(list.get(k));
						if (mShowDate.getYear() == now.get(Calendar.YEAR)) {
							if (mShowDate.getMonth() == now.get(Calendar.MARCH) + 1) {
								if (day == now.get(Calendar.DAY_OF_MONTH)) {
									CustomDate date = CustomDate.modifiDayForObject(mShowDate, day);
									rows[j].cells[i] = new Cell(date, State.MARK_DAY, i, j);
								}
							}
						}

					}

					// ????????
				} else if (position < firstDayWeek) {
					rows[j].cells[i] = new Cell(new CustomDate(mShowDate.year, mShowDate.month - 1, lastMonthDays
							- (firstDayWeek - position - 1)), State.PAST_MONTH_DAY, i, j);
					// ?????
				} else if (position >= firstDayWeek + currentMonthDays) {
					rows[j].cells[i] = new Cell((new CustomDate(mShowDate.year, mShowDate.month + 1, position - firstDayWeek
							- currentMonthDays + 1)), State.NEXT_MONTH_DAY, i, j);
				}
			}
		}
		mCellClickListener.changeDate(mShowDate);
	}
	/**
	 *
	* */
	private void fill() {
		int monthDay = DateUtil.getCurrentMonthDay(); // ??
		int lastMonthDays = DateUtil.getMonthDays(mShowDate.year, mShowDate.month - 1); // ????
		int currentMonthDays = DateUtil.getMonthDays(mShowDate.year, mShowDate.month); // ????
		int firstDayWeek = DateUtil.getWeekDayFromDate(mShowDate.year, mShowDate.month);// ????????
		boolean isCurrentMonth = false;
		if (DateUtil.isCurrentMonth(mShowDate)) {
			isCurrentMonth = true;
		}
		int day = 0;
		for (int j = 0; j < TOTAL_ROW; j++) {
			rows[j] = new Row(j);
			for (int i = 0; i < TOTAL_COL; i++) {
				int position = i + j * TOTAL_COL; // ????????
				// ??????
				if (position >= firstDayWeek && position < firstDayWeek + currentMonthDays) {
					day++;
					rows[j].cells[i] = new Cell(CustomDate.modifiDayForObject(mShowDate, day), State.CURRENT_MONTH_DAY, i, j);
					// ????
					if (isCurrentMonth && day == monthDay) {
						CustomDate date = CustomDate.modifiDayForObject(mShowDate, day);
						rows[j].cells[i] = new Cell(date, State.TODAY, i, j);
					}
					if (isCurrentMonth && day > monthDay) { // ????????????????????????
						rows[j].cells[i] = new Cell(CustomDate.modifiDayForObject(mShowDate, day), State.UNREACH_DAY, i, j);
					}

					for (int k = 0; k < list.size(); k++) {
						now.setTime(list.get(k));
						if (mShowDate.getYear() == now.get(Calendar.YEAR)) {
							if (mShowDate.getMonth() == now.get(Calendar.MARCH) + 1) {
								if (day == now.get(Calendar.DAY_OF_MONTH)) {
									CustomDate date = CustomDate.modifiDayForObject(mShowDate, day);
									rows[j].cells[i] = new Cell(date, State.MARK_DAY, i, j);
								}
							}
						}

					}

					// ????????
				} else if (position < firstDayWeek) {
					rows[j].cells[i] = new Cell(new CustomDate(mShowDate.year, mShowDate.month - 1, lastMonthDays
							- (firstDayWeek - position - 1)), State.PAST_MONTH_DAY, i, j);
					// ?????
				} else if (position >= firstDayWeek + currentMonthDays) {
					rows[j].cells[i] = new Cell((new CustomDate(mShowDate.year, mShowDate.month + 1, position - firstDayWeek
							- currentMonthDays + 1)), State.NEXT_MONTH_DAY, i, j);
				}
			}
		}
		mCellClickListener.changeDate(mShowDate);
	}


    //绘制调用ondraw方法
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		for (int i = 0; i < TOTAL_ROW; i++) {
			if (rows[i] != null) {
				rows[i].drawCells(canvas);
			}
		}
	}
    //获取屏幕设置宽高比
	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);
		mViewWidth = w;
		mViewHeight = h;
		mCellSpaceHeight = mViewHeight/TOTAL_ROW;
		mCellSpace = mViewWidth / TOTAL_COL;
		if (!callBackCellSpace) {
			callBackCellSpace = true;
		}
		mTextPaint.setTextSize(mCellSpaceHeight / 3);
	}
    /**
     *  触控获取坐标
    * */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				mDownX = event.getX();
				mDownY = event.getY();
				break;
			case MotionEvent.ACTION_UP:
				float disX = event.getX() - mDownX;
				float disY = event.getY() - mDownY;
				if (Math.abs(disX) < touchSlop && Math.abs(disY) < touchSlop) {
					col = (int) (mDownX / mCellSpace);
					row = (int) (mDownY / mCellSpaceHeight);
					measureClickCell(col, row);
				}
				break;
			default:
				break;
		}

		return true;
	}

	/**
	 * 日历点击事件
	 *
	 * @param col
	 * @param row
	 */
	private void measureClickCell(int col, int row) {
		if (col >= TOTAL_COL || row >= TOTAL_ROW)
			return;
		if (mClickCell != null) {
			rows[mClickCell.j].cells[mClickCell.i] = mClickCell;
		}
		if (rows[row] != null) {
			mClickCell = new Cell(rows[row].cells[col].date, rows[row].cells[col].state, rows[row].cells[col].i, rows[row].cells[col].j);
			CustomDate date = rows[row].cells[col].date;
			// --------------
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar c = Calendar.getInstance();
			String curTime = sf.format(c.getTime());
			c.add(Calendar.DAY_OF_MONTH, 7);
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			String strClick = date.toString();
			String getmoney = "2016-05-13";
			String strLimit = sf.format(c.getTime()).toString();
			Date dateClick = null;
			Date dateLimit = null;
			Date dateCurrent = null;
			Date datemoney = null;
			try {
				datemoney = formatter.parse(getmoney);
				dateClick = formatter.parse(strClick);
				dateCurrent = formatter.parse(curTime);
				dateLimit = formatter.parse(strLimit);
			} catch (ParseException e) {
				e.printStackTrace();
			}

			date.week = col;
			if (mClickCell.state != State.NEXT_MONTH_DAY && mClickCell.state != State.PAST_MONTH_DAY){
				mCellClickListener.clickDate(date);
				update();
			}
		}
	}

	/**
	 *行绘制
	 *
	 */
	class Row {
		public int j;

		Row(int j) {
			this.j = j;
		}

		public Cell[] cells = new Cell[TOTAL_COL];

		public void drawCells(Canvas canvas) {
			for (int i = 0; i < cells.length; i++) {
				if (cells[i] != null) {
					cells[i].drawSelf(canvas);
				}
			}
		}

	}

	/**
	 *
	 *
	 */
	class Cell {
		public CustomDate date;
		public State state;
		public int i;
		public int j;

		public Cell(CustomDate date, State state, int i, int j) {
			super();
			this.date = date;//日期
			this.state = state;//状态
			this.i = i;//行
			this.j = j;//列
		}
		private boolean flag = false;
        //判断是否有日程
		public void searchDate(){

			if (null == haveScheduleList){
				return;
			}
			//数字的格式转换
			String date_day = String.format("%02d",date.day);
			for (int i = 0;i < haveScheduleList.size();i++){
				String StartTimeString = haveScheduleList.get(i).toString();
				String[] StartTime = StartTimeString.replace(" ","-").split("-");

				if (StartTime[2].equals(date_day)) {

					flag = true;
					return;
				}
				flag = false;

			}
		}
		/**
         * 绘制自身样式方法
         * *****/
		public void drawSelf(Canvas canvas) {

			switch (state) {
				case CHECKED_DAY: // 点击的时间点画
					customPaint(Style.FILL, Color.parseColor("#eeaf49"), Color.parseColor("#fffffe"), canvas);
					isSchePaint(Style.FILL, Color.parseColor("#eeaf49"), canvas);
					break;
				case CURRENT_MONTH_DAY: // 当前 天的这个月的后面不画
					mTextPaint.setColor(Color.BLACK);
					isSchePaint(Style.FILL, Color.parseColor("#eeaf49"), canvas);
					break;
				case PAST_MONTH_DAY:
				case NEXT_MONTH_DAY: // 隐藏的天
					mTextPaint.setColor(Color.parseColor("#c7c8cc"));
					//isSchePaint(Paint.Style.FILL, Color.parseColor("#eeaf49"), Color.parseColor("#000000"), canvas);
					break;
				case UNREACH_DAY: // 这个月当天的后面
					mTextPaint.setColor(Color.BLACK);
					isSchePaint(Style.FILL, Color.parseColor("#eeaf49"), canvas);
					break;
				case TODAY:// 今天
					customPaint(Style.FILL, Color.parseColor("#89bf4f"), Color.parseColor("#fffffe"), canvas);
					isSchePaint(Style.FILL, Color.parseColor("#eeaf49"), canvas);
					break;
				case MARK_DAY:// ??????
					customPaint(Style.STROKE, Color.parseColor("#F39700"), Color.parseColor("#F39700"), canvas);
					//isSchePaint(Paint.Style.FILL, Color.parseColor("#eeaf49"), Color.parseColor("#000000"), canvas);
					break;

				default:
					break;
			}
			//(mTextPaint.getFontMetricsInt().top-mTextPaint.getFontMetricsInt().bottom)/2
			//
			String content = date.day + "";
			canvas.drawText(content, (float) ((i + 0.5) * mCellSpace - mTextPaint.measureText(content) / 2), (float) ((j + 0.5)
					* mCellSpaceHeight+(mTextPaint.measureText(content, 0, 1) )/ 2), mTextPaint);
		}

		/**
		 * 样式
		 *
		 * @param cirleStyle
		 * @param cirlePaintColor
		 * @param textPaintColor
		 * @param canvas
		 */
		public void customPaint(Style cirleStyle, int cirlePaintColor, int textPaintColor, Canvas canvas) {
			mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
			mCirclePaint.setAntiAlias(true);
			mCirclePaint.setStyle(cirleStyle);// 样式
			mCirclePaint.setColor(cirlePaintColor); // 圆圈颜色
			mTextPaint.setColor(textPaintColor);// 字体颜色
			canvas.drawCircle((float) (mCellSpace * (i + 0.5)), (float) ((j + 0.5) * mCellSpaceHeight), mCellSpaceHeight/3, mCirclePaint);

		}
		//有日程标志样式
		public void isSchePaint(Style cirleStyle, int cirlePaintColor, Canvas canvas) {
			searchDate();
			if (flag == true){
				mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
				mCirclePaint.setAntiAlias(true);
				mCirclePaint.setStyle(cirleStyle);// 样式
				mCirclePaint.setColor(cirlePaintColor); // 圆圈颜色
				canvas.drawCircle((float) (mCellSpace * (i + 0.5)), (float) (((j + 0.5) * mCellSpaceHeight) + (mCellSpaceHeight-mCellSpaceHeight/2)), mCellSpace /14, mCirclePaint);
			}
		}
	}

	/**
	 *日期状态标示
	 */
	enum State {
		TODAY, CURRENT_MONTH_DAY, PAST_MONTH_DAY, NEXT_MONTH_DAY, UNREACH_DAY, CHECKED_DAY, MARK_DAY
	}

	//  左滑
	public void leftSlide(List<String> scheduleList) {
		haveScheduleList.clear();
		haveScheduleList= scheduleList;
		//Log.e("hjy",haveScheduleList+"");
		if (mShowDate.month == 1) {
			mShowDate.month = 12;
			mShowDate.year -= 1;
		} else {
			mShowDate.month -= 1;
		}
		//update();
		fill();
		invalidate();
	}

	// 右滑
	public void rightSlide(List<String> scheduleList) {

		haveScheduleList.clear();
		haveScheduleList = scheduleList;
		//Log.e("hjy",haveScheduleList+"");
		if (mShowDate.month == 12) {
			mShowDate.month = 1;
			mShowDate.year += 1;
		} else {
			mShowDate.month += 1;
		}
		// update();
		fill();
		invalidate();
	}

	public void centerSlide(List<String> scheduleList){
		haveScheduleList.clear();
		haveScheduleList = scheduleList;
		fill();
		invalidate();
	}

	public void update() {
		fillDate();
		invalidate();

	}
    //初始化数据
	public void initDate(List<String> scheduleList) {
		haveScheduleList.clear();
		haveScheduleList = scheduleList;
		//当删除到最后一条数据时重绘
		if (0 == haveScheduleList.size()){
            fillDate();
        }
		invalidate();
	}

}
